package com.xxxx.server.service.impl;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.xxxx.server.service.IFileUploadService;
import com.xxxx.server.utils.AssertUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;

/**
 * @Author 乔通
 * @Date 2020/10/19 17:57
 * Created by IntelliJ IDEA 2020.1.
 * Project: yeb
 * Description：文件上传实现类
 */
@Service
public class FileUploadServiceImpl implements IFileUploadService {
    private static final String ACCESS_KEY="o40F4_cjGRWLZ1cRp7ePRTj_EFcgoiUc_2XKU_5a";
    private static final String SECRET_KEY="mYMiuOYXFsAiK5MjMqAwAAdbJUvSUgPDepmAl4BK";
    private static final String BUCKET="yebpicture";
    //CDN域名
    private static final String CDN_DOMAIN_NAME="qifw43ez9.hn-bkt.clouddn.com";

    /**
     * 文件上传
     * @param file
     * @return 文件在七牛云上的url
     */
    @Override
    public String fileUpload(MultipartFile file) {
        String filePath=null;

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region2());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = ACCESS_KEY;
        String secretKey = SECRET_KEY;
        String bucket = BUCKET;
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;

        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(file.getInputStream(),key,upToken,null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            //System.out.println(putRet.key);
            //设置文件存在七牛云服务器后返回的文件名
            filePath=putRet.key;
            //System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        AssertUtil.isTrue(null==filePath,"文件上传失败");
        //文件url
        String url = "http://"+CDN_DOMAIN_NAME+"/"+filePath;
        return url;
    }
}
